<template>
  <div class="page-main">
    <query-page
      ref="detailTable"
      v-model:selectedKeys="selectedKeys"
      title="三码验证管理"
      :form-component-config="formComponentConfig"
      :form-render-config="formRenderConfig"
      :form-render-keys="formRenderKeys"
      :table-component-config="tableComponentConfig"
      :table-render-config="tableRenderConfig"
      :table-render-keys="tableRenderKeys"
      :loading="isLoading"
      :data="renderData"
      :total="tableTotal"
      :row-class="rowClassFun"
      row-selection-type="checkbox"
      @selection-change="selectionChange"
      @query-data="getData"
    >
      <template #container-side>
        <a-space>
          <a-button
            v-permission="['pms:dcd-sn-mian:Revoke']"
            :disabled="!selectedKeys.length"
            @click="handleRevoke"
            >撤销</a-button
          >
          <div class="nocontact r-color">
            <span class="icon r-bg-color"></span>
            不能关联
          </div>
          <div class="contact g-color">
            <span class="icon g-bg-color"></span>
            能关联
          </div>
        </a-space>
      </template>
      <template #operate="{ record, rowIndex }">
        <a-button type="text" @click="handleDetail(record, rowIndex)"
          >详情</a-button
        >
        <a-button
          v-permission="['pms:receive-detail-batch:updateAll']"
          type="text"
          :hidden="!['0', '10'].includes(record.billStatus)"
          @click="handleEdit(record, rowIndex)"
          >编辑</a-button
        >
        <a-button
          v-permission="['pms:dcd-sn-mian:bind']"
          type="text"
          :hidden="!['0', '10'].includes(record.billStatus)"
          @click="bindingItem(record, rowIndex)"
          >绑定预到货</a-button
        >
        <a-button
          v-permission="['pms:dcd-sn-mian:deleteReceivedetailBatch']"
          type="text"
          :hidden="!['0', '10'].includes(record.billStatus)"
          @click="deleteLeft(record, rowIndex)"
          >删除</a-button
        >
      </template>
    </query-page>
    <BindModal
      v-if="bindModelVisible"
      v-model="bindModelVisible"
      :select-id="selectId"
      @fetch-data="getData"
    ></BindModal>
    <EditModal
      v-if="editModelVisible"
      v-model="editModelVisible"
      :select-id="selectBatchId"
      @fetch-data="getData"
    ></EditModal>
    <DetailModal
      v-if="detailModelVisible"
      v-model="detailModelVisible"
      :select-id="selectId"
    ></DetailModal>
  </div>
</template>

<script lang="ts" setup>
  import { computed, defineAsyncComponent, provide, reactive, ref } from 'vue';
  import queryPage from '@/common/components/query-page/index.vue';
  import { Message } from '@arco-design/web-vue';
  import { info } from '@/common/utils/modal-promise';
  import {
    getPmsDcdPageDetail,
    deletePmsBatch,
    revokePmsBatch,
  } from '@/api/purchaseArrival/threeCodeVerification';
  import {
    formComponentConfig,
    formRenderConfig,
  } from '../moduleCommon/formComp/baseFormConfig';
  import {
    tableRenderConfig,
    tableComponentConfig,
  } from '../moduleCommon/tableComp/baseTableConfig';

  // 异步加载组件
  const BindModal = defineAsyncComponent(() => import('./BindModal.vue'));
  const EditModal = defineAsyncComponent(
    () => import('../purchaseArrivalDetails/EditModal.vue')
  );
  const DetailModal = defineAsyncComponent(() => import('./DetailModal.vue'));
  // 当前页面要渲染的查询条件
  const formRenderKeys = [
    'orderNo1',
    'mdsVendorCode',
    'mdsVendorName',
    'mdsItemCode',
    'mdsItemName',
    'proMdsItemId',
    'sysOrderNo',
    'barcode1',
    'barcodeStatus',
    'barScanItemResult',
    'barScanProdResult',
    'scanImpUserId',
    'scanImpDateBegin',
    'scanImpDateEnd',
    'marque',
    'itemSerialNo',
  ];
  // 当前表格要渲染哪些值
  const tableRenderKeys = [
    'index',
    'secretLevel',
    'barcode1',
    'filed1', // 能否关联物品码和单件信息
    'filed2', // 三码验证结果
    'formateBatchFlag', // 到货明细登记确认
    'mdsItemCode',
    'mdsItemName',
    'partQty',
    'reqQty',
    'recprtlotNo',
    'batchNo',
    'itemSerialNo',
    'suplyStatus',
    'invReceiveQty',
    'pmsReceiveQty',
    'lfackoryDate',
    'manuDate',
    'mdsInventoryName',
    'invDateNum',
    'archiveDate',
    'preservationTime1',
    'acceptanceDate',
    'lifetimeNum',
    'scanfFirstDate',
    'scanfUseDate',
    'scanfSureDate',
    'weight',
    'weightUnit',
    'threeStartDate',
    'storageDate',
    'oilSealDate',
    'recheckDate',
    'pmsReceiveDate',
    'arrivalDate',
    'checkTimeType',
    'mdsUnitRate',
    'operate',
  ];
  const isLoading = ref(true);
  const editModelVisible = ref(false);
  const detailModelVisible = ref(false);
  const renderData = ref<any[]>([]);
  const selectedKeys = ref([]);
  const tableTotal = ref(0);
  const bindModelVisible = ref(false);
  const selectId = ref(null);
  const detailTable = ref(null);
  const selectBatchId = ref(null);
  let selectBatchRow = reactive({});
  provide(
    'selectBatchRow',
    computed(() => {
      return selectBatchRow;
    })
  );
  const getData = async (queryInfo: object) => {
    const page = detailTable.value.getStatus();
    renderData.value = [];
    selectedKeys.value = [];
    isLoading.value = true;
    const { data } = await getPmsDcdPageDetail({
      ...queryInfo,
      ...page,
    });
    // set两个值
    data.list = data.list.map((row) => {
      let filed1 = '';
      let color = 'green';
      if (row.barScanProdResult === 'N') {
        filed1 += '机载单件码没有找到，';
        color = 'red';
      } else {
        filed1 += '机载单件码解析成功，';
      }
      if (row.barScanItemResult === 'N') {
        filed1 += '物品码没有找到';
        color = 'red';
      } else {
        filed1 += '物品码解析成功';
      }
      let filed2 = '';
      if (row.barScanProdResult === 'N') {
        filed2 = '无单件信息';
      }
      if (row.barScanItemResult === 'N') {
        filed2 = '无物品信息';
      }
      if (row.barScanProdResult !== 'N' && row.barScanItemResult !== 'N') {
        filed2 = '验证成功';
      }
      return {
        ...row,
        filed1,
        filed2,
        color,
      };
    });
    renderData.value = data.list;
    tableTotal.value = data.total;
    isLoading.value = false;
  };
  const rowClassFun = (val) => {
    return val.raw.color;
  };
  // const showConsole = (rowData: object, index: number) => {
  //   console.log('rowData', rowData);
  //   console.log('index', index);
  // };
  const handleRevoke = async () => {
    if (!selectedKeys.value.length) {
      Message.info({
        content: '请选择三码信息！',
        duration: 5 * 1000,
      });
      return;
    }
    const form = {
      receiveDetailBatchIdList: selectedKeys?.value,
      receiveDetailId: null,
    };
    await revokePmsBatch(form);
    selectedKeys.value = [];
    Message.success({
      content: '撤销成功！',
      duration: 5 * 1000,
    });
    getData();
  };
  const handleEdit = (row) => {
    selectBatchRow = Object.assign(selectBatchRow, row);
    selectBatchId.value = row.id;
    editModelVisible.value = true;
  };
  const handleDetail = (row) => {
    selectId.value = row.pmsReceiveDetailId;
    detailModelVisible.value = true;
  };
  const bindingItem = (val) => {
    // console.log('selectedKeys', val);
    selectId.value = val.id;
    selectBatchRow = Object.assign(selectBatchRow, val);
    bindModelVisible.value = true;
  };
  const deleteLeft = async (row) => {
    await info({
      title: '删除确认',
      content: '您确定要删除当前所选的数据？',
      okText: '确认',
    });
    const { id } = row;
    await deletePmsBatch([id]);
    Message.success({
      content: '删除成功！',
      duration: 5 * 1000,
    });
    getData();
  };
</script>

<style lang="less" scoped>
  @import url('../moduleCommon/common.less');

  /deep/ .green :nth-child(4) {
    background-color: #8fda94 !important;
  }

  /deep/ .red :nth-child(4) {
    background-color: #ee8d82 !important;
  }
</style>
